import GameConfig from "../GameConfig";
import { ScrollProgressBar } from "../NRLib/Component/ScrollProgressBar";
import DebugExt from "../NRLib/base/DebugExt";
import GlobalImg from "../NRLib/base/GlobalImg";
import MutiLanguage from "../NRLib/base/MutiLanguage";
import UILangData, { SimpleLangData } from "../NRLib/base/UILangData";
import LangImg from "../NRLib/ccExt/LangImg";
import ZegoEvents from "./ZegoEvents";

const { ccclass, property, menu } = cc._decorator;

/**
 * Web版第三方登录场景脚本
 */
@ccclass
@menu('Login/LoginSceneWeb')
export default class LoginSceneWeb extends cc.Component {

    // 纯白纹理（框架做场景切换过度变色用）
    @property(cc.SpriteFrame)
    private readonly singleColor: cc.SpriteFrame = null;

    // progressBar
    @property(ScrollProgressBar)
    private readonly progressBar: ScrollProgressBar = null;

    // 登录相关信息文本
    @property(cc.Label)
    private readonly loginMsg: cc.Label = null;

    @property(cc.Prefab)
    private readonly messagebox: cc.Prefab = null;

    @property(cc.Sprite)
    private readonly tempAvatar: cc.Sprite = null;

    // 自定义多语言信息
    private _langData: UILangData = null;

    // LIFE-CYCLE CALLBACKS:

    private checkYYLanguage() {
        const pkgid = yy.lobby.getPackageID();
        if (pkgid != "zego" && pkgid != "yygame" || CC_PREVIEW) {
            const p = yy.gf.getURLParam();
            if (p && p.language && p.language.length > 0) {
                yy.setCurrentLanguage(p.language);
            }
            else {
                yy.setCurrentLanguage("en");
            }
        }

        // 校验是否支持当前语言，不再支持列表中的，改为默认英文
        const lanList = GameConfig.langList;
        if (lanList.indexOf(yy.curLanguage) < 0) {
            yy.setCurrentLanguage("en");
        }
        // 预加载游戏多语言图片资源（主游戏+子游戏）
        const subGames = "MapMasterID" in GameConfig ? [GameConfig.MapMasterID.toString()] : [];
        LangImg.getIns().preload([yy.curLanguage], subGames);
    }

    onLoad() {
        if (CC_DEBUG) {
            yy.pv.gCfg.mainGameID = GameConfig.GameID;
            console.log("LoginSceneWeb -- onVersionCheckComplete ", GameConfig.GameID);
        }
        // 仅zego需要登录进度打点
        globalThis.isFirstEnter = GameConfig.isZEGO;
        DebugExt.tips("Game Version：", GameConfig.version);
        // 兼容老项目，未配置该属性则默认英语为备选语言
        const baseLang: string = "baseLang" in GameConfig ? GameConfig.baseLang as string : "en";
        MutiLanguage.getIns().init(GameConfig.langList, baseLang, "language/gameData");
        LangImg.getIns().init(GameConfig.langList, baseLang);

        // 全局通用资源目录加载
        const propIconsPath: string = "propIconsPath" in GameConfig ? GameConfig.propIconsPath as string : "";
        if (propIconsPath)
            GlobalImg.getIns().init(propIconsPath);

        // 注册消息框
        if (this.messagebox)
            yy.ui.manager.setMessageBoxPrefab(this.messagebox);

        // 初始化进度条
        this.progressBar.active = false;
        this.loginMsg.string = ""; // loginMsg

        // 给框架注册一些场景和纹理资源
        yy.ui.manager.setSingleColorSpriteFrame(this.singleColor);
        yy.ui.manager.setSceneFire(yy.SceneType.Login, "LoginScene", null);

        // 监听版本检查
        yy.event.on(this, yy.event.lobby.VersionCheckComplete, this.onVersionCheckComplete);
        // 监听登录大厅结果事件
        yy.event.on(this, yy.event.lobby.LoginLobbyResult, this.onLoginLobbyResult);
    }

    protected start(): void {
        // 游戏首屏加载成功并开始展示事件
        window.parent.postMessage("loadCompleted", '*');

        this.checkYYLanguage();
        // 拉起loading
        yy.ui.manager.showPublicUI(yy.UIType.Loading);
        this.initLanguage();

        // 拉起进度条动画--第一段
        this.progressBar.scrollTo(1, 0.4);
        this.progressBar.active = true;
        globalThis.isFirstEnter && yy.thirdPlatform.onLoadingEvent({ type: "loading_progressBar", value: '0' });

        // 补充一次登陆检测，防止重新登陆重连时 未接收到VersionCheckComplete事件
        this.scheduleOnce(() => {
            if (yy.lobby.getLoginState() == yy.LoginState.Unlogin) {
                this.loginMsg.string = '';
                yy.lobby.reqLoginLobby();
                this.progressBar.scrollTo(0.5, 0.49);
                if (CC_DEBUG) console.log("开始登录游戏！");
            }
        }, 0.5);
    }

    // 版本检测完成回调
    private onVersionCheckComplete(e: yy.event.lobby.VersionCheckComplete) {
        // web版，不需要热更新等操作
        this.loginMsg.string = '';
        this.scheduleOnce(this.loginDefultAccunt, 0);
        // 拉起进度条第二段
        this.progressBar.scrollTo(0.5, 0.49);
    }

    // 登录默认账号
    private loginDefultAccunt() {
        if (yy.lobby.getLoginState() == yy.LoginState.Logined) {
            yy.lobby.reqLogoutLobby();
        }

        yy.lobby.reqLoginLobby();
        globalThis.isFirstEnter && yy.thirdPlatform.onLoadingEvent({ type: "loading_progressBar", value: "49" });
        if (CC_DEBUG) console.log("开始登录游戏！");
    }

    // 登录回调
    private onLoginLobbyResult(e: yy.event.lobby.LoginLobbyResult) {
        // 登录成功
        if (e.bSucceed) {
            if (CC_DEBUG) console.log("登录成功，userID:", yy.myself.userID);
            // zego提前加载第三方头像时机
            if (GameConfig.isZEGO && this.tempAvatar)
                yy.faceCenter.bindUserFace(this.tempAvatar, yy.myself.userID);

            // 进度条动画设置
            this.progressBar.scrollTo(0.1, 0.5);
            yy.lobby.setPlayMoneyID(GameConfig.COIN);

            this._isLogined = true;
            this.preloadScene();
            const gameInfo = yy.getGameInfo(GameConfig.GameID);
            if (gameInfo.rooms.length == 0)
                gameInfo.updateRoomList();
        }
        else {
            // 登录失败，显示原因给用户
            this.loginMsg.string = e.errorDesc;
            this.progressBar.active = false;
            yy.ui.manager.hidePublicUI(yy.UIType.Loading);
            ZegoEvents.loadGame(false);

            const str = this._langData.getString("LoginFaild") || e.errorDesc;
            yy.ui.messageBox(str, (btn: yy.MBBtn) => {
                if (btn == yy.MBBtn.Yes) {
                    const pkgid = yy.lobby.getPackageID();
                    if (pkgid == "guochao") {
                        // 郑州国超渠道，约定特殊处理
                        console.log(pkgid, " 渠道，传递指定消息 restartGame");
                        window.parent.postMessage("restartGame", '*');
                    }
                    else
                        this.loginDefultAccunt();
                }
                else
                    ZegoEvents.exitGame();
            }, this, yy.MBBtnType.YesNo);
            if (CC_DEBUG) console.log("登录失败：", e.errorDesc, e.errorCode);
        }
    }

    private _isPreLoaded: boolean = false;
    private _isLogined: boolean = false;
    private _resPrecent = 0;
    /** 预加载场景文件 */
    private preloadScene() {
        const name: string = ZegoEvents.gameSceneName;
        yy.ui.manager.setSceneFire(yy.SceneType.Game, name, null);
        cc.director.preloadScene(name,
            (completedCount: number, totalCount: number, item: any) => {
                const precent = completedCount / totalCount;
                if (precent > this._resPrecent) {
                    this._resPrecent = precent;
                    this.progressBar.value = 0.5 + precent / 2;
                }
            },
            (error: Error, asset: cc.SceneAsset) => {
                if (!error) {
                    globalThis.isFirstEnter && yy.thirdPlatform.onLoadingEvent({ type: "loading_progressBar", value: '100' });
                    this._isPreLoaded = true;
                    if (this._isLogined)
                        ZegoEvents.enterGame();
                    ZegoEvents.loadGame(true);
                }
                else {
                    const tips: string = this._langData.getString("LoadGameFaild");
                    yy.ui.messageBox(tips, (btn: yy.MBBtn) => {
                        if (btn == yy.MBBtn.Yes)
                            this.preloadScene();
                        else
                            ZegoEvents.exitGame();
                    }, this, yy.MBBtnType.YesNo);
                    ZegoEvents.loadGame(false);
                }
            }
        );
    }

    private initLanguage() {
        // UILangData
        if (!this._langData) {
            this._langData = new UILangData(GameConfig.langList, "en");
            const json: SimpleLangData = {
                "LoginFaild": {
                    "en": "Login failed. Please try again later.",
                    "zh": "登录失败，请稍后重新尝试！",
                    "zhf": "登錄失敗，請稍後重試！",
                    "jp": "ログインに失敗しました。後で再試行してください！",
                    "id": "Login gagal. Silakan coba lagi nanti.",
                    "hi": "लॉगिन विफल हुआ। कृपया बाद में पुनः प्रयास करें।",
                    "pt": "Login falhou. Por favor, tente novamente mais tarde.",
                    "es": "El inicio de sesión falló. Por favor, inténtalo de nuevo más tarde.",
                    "ru": "Вход не удался. Пожалуйста, попробуйте позже.",
                    "ar": "فشل تسجيل الدخول. يرجى المحاولة مرة أخرى لاحقًا.",
                    "ms": "Gagal log masuk. Sila cuba lagi nanti."
                },
                "LoadGameFaild": {
                    "en": "Failed to load game scene!",
                    "zh": "加载游戏场景失败！",
                    "zhf": "載入遊戲場景失敗！",
                    "jp": "ゲームシーンの読み込みに失敗しました！",
                    "id": "Gagal memuat adegan permainan!",
                    "hi": "गेम सीन लोड करने में विफल!",
                    "pt": "Não foi possível carregar a cena do jogo!",
                    "es": "No se pudo cargar la escena del juego!",
                    "ru": "Не удалось загрузить сцену игры!",
                    "ar": "فشل في تحميل مشهد اللعبة!",
                    "ms": "Gagal memuatkan adegan permainan!"
                }
            };
            this._langData.setJsonLangData(json);
        }
    }

}
